//录面板
var gridPanel;
//表单窗口
var contentPanel;
//单面板
var formPanel;
//页面布局管理器
var viewport = null;
//服务处理标志
var processFlag = false;

Date.prototype.toString=function(){ 
  return this.format("Ymd"); 
};

var configFormWindow;
var configFormPanel;
var uploadFormWindow;
var uploadFormPanel;

var recordDef = Ext.data.Record.create([{name:'code'},{name:'name'}]);
var dataStore = new Ext.data.Store({
	proxy:new Ext.data.HttpProxy({url:'/getAllEnviroments'}),
	reader:new Ext.data.JsonReader({id:'code',root:'comboBox'},recordDef),
	remoteStore:true
});
var dataStore1 = new Ext.data.Store({
	proxy:new Ext.data.HttpProxy({url:'/getAllEnviroments?excludeAll=true'}),
	reader:new Ext.data.JsonReader({id:'code',root:'comboBox'},recordDef),
	remoteStore:true
});
var projectDataStore = new Ext.data.Store({
	proxy:new Ext.data.HttpProxy({url:'/getApplications'}),
	reader:new Ext.data.JsonReader({id:'code',root:'comboBox'},recordDef),
	remoteStore:true
});

//格式化日期  
function formatDate(value) {  
    if (Ext.isEmpty(value)) {//判断是否是日期类型的数据  
        return '';  
    } else {  
        if (Ext.isDate(value)){  
        	alert("1  "+value+"  "+Ext.util.Format.date(value, 'Ymd'));
            return ""+Ext.util.Format.date(value, 'Ymd');// 用于时间控件返回值  
        }
        else  {  
        	alert("2  "+value+"  "+Ext.util.Format.date(new Date(value), 'Ymd'));
            return Ext.util.Format.date(new Date(value), 'Ymd');// 转换为Date类型  
        }
    }  
} 

//创建活动面板
function createGridPanel(){
	//检查对象是否已经创建
	if( gridPanel!=null ) return;
	//设置数据源
	var ds = new Ext.data.Store({
		proxy : new Ext.data.HttpProxy({url:systemContext + '/appversion/page'}),
		reader: new Ext.data.JsonReader({
				root: 'records',
				totalProperty: 'total',
				id: 'id'
			},
			['id','appId','appName','envType','description','isPublic','memo','version','createTime']
		)
	});

	//列选择模式
	var sm = new Ext.grid.CheckboxSelectionModel();
	//列表名
	var colModel = new Ext.grid.ColumnModel([        
        new Ext.grid.RowNumberer({header:"序号",width:30}),
        sm,
        {header:"版本ID",dataIndex:"id",width:50},
        {header:"应用代码",dataIndex:"appName",width:120,editor: new Ext.form.TextField({allowBlank: false})},
        {header:"应用名称",dataIndex:"description",width:160,editor: new Ext.form.TextField({allowBlank: false})},
        {header:"环境",dataIndex:"envType",width:100,editor: new Ext.form.TextField({allowBlank: false}),renderer:function(value){
        	if( value=='dev'){
        		return '开发环境';
        	}else if( value=='test'){
        		return '测试环境';
        	}else if( value=='stat'){
        		return '预发布环境';
        	}else if( value=='prod'){
        		return '生产环境';
        	}else{
        		return '其他';
        	}
        }},
		{header:"是否为公共配置",dataIndex:"isPublic",width:100,renderer:function(value){
        	if( value=='1'){
        		return '公共配置';
        	}else {
        		return '应用配置';
        	}
        }},
		{header:"版本",dataIndex:"version",width:80,editor: new Ext.form.TextField({allowBlank: true})},
        {header:"备注",dataIndex:"memo",width:120,editor: new Ext.form.TextField({allowBlank: false})},
        {header:"创建时间",dataIndex:"createTime",width:160}
    ]);
	colModel.defaultSortable = true;
	//创建grid面板
	gridPanel = new Ext.grid.EditorGridPanel({
			border:false,
			buttonAlign :'left',
			loadMask: true,
			store: ds,
			autoExpandColumn:8,
			height:'100%',
			autoWidth:false,
			cm: colModel,
			sm: sm,
			autoScroll: true,
			tbar: [
				'环境：',{xtype:'tbseparator'},new Ext.form.ComboBox({
				    store: dataStore,
				    displayField:'name',
				    valueField:'code',
				    typeAhead: true,
				    mode: 'remote',
				    editable:false,
				    hiddenName:'envType',
					width:70,
				    triggerAction: 'all',
				    emptyText:'全部',
				    selectOnFocus:true,
					anchor:'80%',
					name : 'envType',
					listeners: {
			            select: function(combo, record, index) {
			            	envType = combo.getValue();
			            	projectDataStore.removeAll();
			            	projectDataStore.load({params:{envType: envType}});
			            }
			        }
				}),
				'应用：',{
					xtype : 'combo',
					store : projectDataStore,
					displayField : 'name',
					valueField : 'code',
					typeAhead : true,
					mode : 'remote',
					triggerAction : 'all',
					width: 200,
					emptyText : '请选应用...',
					selectOnFocus : true,
					resizable : true,
					hiddenName : 'appId',
					listeners:{
						focus:function(combo,record,index){
							projectDataStore.load({params:{envType: Ext.get('envType').dom.value}});
			            }
			        }
				},{xtype:'tbseparator'},
				'版本：',{xtype:'textfield',width:80,id:'version',name:'version'},{xtype:'tbseparator'},
				{text:'搜索',iconCls:'icon-search',handler:function(){
					ds.load({
				    	params:{start:0, limit:50,envType:Ext.get('envType').dom.value,appId:Ext.get('appId').dom.value,
				    		version:Ext.get('version').dom.value}
				    });
				}},{xtype:'tbseparator'},
				{text:'删除版本',iconCls:'rec_delete',handler:function(gridPanel){
					if( ds.getCount()==0 ) {
						Ext.MessageBox.alert('提示','无记录，无法删除！');
						return;
					}
					var records = sm.getSelections();
					if( records.length==0 ) {
						Ext.MessageBox.alert('提示','未选择记录，无法删除！');
						return;
					}
					Ext.MessageBox.confirm('确认对话框', '确认删除选中应用吗？', function(btn){
			    		if(btn=='yes'){
			    			delRecords(records);
			    		}
					});
				}},{xtype:'tbseparator'},
				{text:'导出版本配置(pro)',iconCls:'rec_add',handler:function(){
					if( ds.getCount()==0 ) {
						Ext.MessageBox.alert('提示','无记录，无法导出！');
						return;
					}
					var records = sm.getSelections();
					if( records.length==0 ) {
						Ext.MessageBox.alert('提示','未选择记录，无法导出！');
						return;
					}
					Ext.MessageBox.confirm('确认对话框', '确认导出选中应用版本配置吗？', function(btn){
			    		if(btn=='yes'){
			    			exportApplications(records,"properties");
			    		}
					});
				}},{xtype:'tbseparator'},
				{text:'导出版本配置(yaml)',iconCls:'rec_add',handler:function(){
					if( ds.getCount()==0 ) {
						Ext.MessageBox.alert('提示','无记录，无法导出！');
						return;
					}
					var records = sm.getSelections();
					if( records.length==0 ) {
						Ext.MessageBox.alert('提示','未选择记录，无法导出！');
						return;
					}
					Ext.MessageBox.confirm('确认对话框', '确认导出选中应用版本配置吗？', function(btn){
			    		if(btn=='yes'){
			    			exportApplications(records,"yml");
			    		}
					});
				}},{xtype:'tbseparator'}
				],
			bbar : new Ext.PagingToolbar({
				pageSize: 50,
				store: ds,
				displayInfo: true,
				displayMsg: '第{0} 到 {1} 条数据 共{2}条',
				emptyMsg: '未查询到资源'
			})
	});
	//加载数据
	ds.load({params:{start:0, limit:50}});
	ds.on('beforeload',function(){ 
	 		Ext.apply(this.baseParams,{envType:Ext.get('envType').dom.value,appId:Ext.get('appId').dom.value
	 			,version:Ext.get('version').dom.value}
	  	);
	});
}

// 创建活动内容面板
function createContentPanel(){
	this.contentPanel = new Ext.Panel({
		split : true,
		bodyStyle : "width:100%",
		region : 'center',
		layout:'fit',
		margins : '0 0 0 0',
		forceFit : true,
		stripeRows : true,
	    enableTextSelection : true 
	});
}

//页面初始化
function init(){
	// 创建对象
	this.createContentPanel();
	this.createGridPanel();
	this.contentPanel.add(this.gridPanel);
	//布局管理器
	this.viewport = new Ext.Viewport({
			layout:'border',
			border:true,
			items:[this.contentPanel]
	});
	this.viewport.render();
}

//删除选中的
function delRecords(records){
	var ids = new Array();
	var index = 0;
	for( var i=0;i<records.length;i++ ){
		ids.push(records[i].get('id'));
	}
	if( ids.length==0 ){
		processFlag = false;
		return;
	}
	processFlag = true;
	this.showWaitingBar();
	Ext.Ajax.request({// 排列顺序
		url : systemContext + '/appversion/deleteAppVersion',
		params : {
			ids : ids
		},
		method : 'POST',
		success : function(response,action) {
			processFlag = false;
			var responseArray = Ext.util.JSON.decode(response.responseText);
			Ext.MessageBox.alert('提示框',responseArray.respMsg);
			gridPanel.getStore().load({
				params:{start:0, limit:50}
			});
		},
		failure : processFailure
	});
}

/**导出应用配置**/
function exportApplications(records,type){
	var params = '';
	for( var i=0;i<records.length;i++ ){
		params += records[i].get('id') + ',';
	}
	window.open('/appversion/exportApplications?ids=' + params + '&type=' + type);
}
